{
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python_defaultSpec_1600654873172",
   "display_name": "Python 3.7.4 64-bit ('base': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2,
 "cells": [
  {
   "source": [
    "# 交叉验证"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn import datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "digits = datasets.load_digits()\n",
    "X = digits.data\n",
    "y = digits.target"
   ]
  },
  {
   "source": [
    "## 测试train_test_split"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=666)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "best k =  3\nbest p =  4\nbest score =  0.9860917941585535\n"
    }
   ],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "best_score, best_p, best_k = 0, 0, 0\n",
    "for k in range(2, 11):\n",
    "    for p in range(1, 6):\n",
    "        knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=k, p=p)\n",
    "        knn_clf.fit(X_train, y_train)\n",
    "        score = knn_clf.score(X_test, y_test)     \n",
    "        if score > best_score:\n",
    "            best_score, best_p, best_k = score, p, k\n",
    "print(\"best k = \", best_k)\n",
    "print(\"best p = \", best_p)\n",
    "print(\"best score = \", best_score)"
   ]
  },
  {
   "source": [
    "## 使用交叉验证"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "array([0.98895028, 0.97777778, 0.96629213])"
     },
     "metadata": {},
     "execution_count": 10
    }
   ],
   "source": [
    "from sklearn.model_selection import cross_val_score\n",
    "\n",
    "knn_clf = KNeighborsClassifier()\n",
    "cross_val_score(knn_clf, X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "best k =  2\nbest p =  2\nbest score =  0.9823599874006478\n"
    }
   ],
   "source": [
    "best_score, best_p, best_k = 0, 0, 0\n",
    "for k in range(2, 11):\n",
    "    for p in range(1, 6):\n",
    "        knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=k, p=p)\n",
    "        scores = cross_val_score(knn_clf, X_train, y_train)\n",
    "        score = np.mean(scores)   \n",
    "        if score > best_score:\n",
    "            best_score, best_p, best_k = score, p, k\n",
    "print(\"best k = \", best_k)\n",
    "print(\"best p = \", best_p)\n",
    "print(\"best score = \", best_score)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_knn_clf = KNeighborsClassifier(weights='distance', n_neighbors=2, p=2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.980528511821975"
     },
     "metadata": {},
     "execution_count": 13
    }
   ],
   "source": [
    "best_knn_clf.fit(X_train, y_train)\n",
    "best_knn_clf.score(X_test, y_test)"
   ]
  },
  {
   "source": [
    "## 回顾网格搜索"
   ],
   "cell_type": "markdown",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "Fitting 3 folds for each of 45 candidates, totalling 135 fits\n[Parallel(n_jobs=1)]: Using backend SequentialBackend with 1 concurrent workers.\n[Parallel(n_jobs=1)]: Done 135 out of 135 | elapsed:   33.3s finished\n"
    },
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "GridSearchCV(cv='warn', error_score='raise-deprecating',\n             estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30,\n                                            metric='minkowski',\n                                            metric_params=None, n_jobs=None,\n                                            n_neighbors=10, p=5,\n                                            weights='distance'),\n             iid='warn', n_jobs=None,\n             param_grid=[{'n_neighbors': [2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],\n             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n             scoring=None, verbose=1)"
     },
     "metadata": {},
     "execution_count": 16
    }
   ],
   "source": [
    "from sklearn.model_selection import GridSearchCV\n",
    "\n",
    "param_grid = [\n",
    "    {\n",
    "        'weights':['distance'],\n",
    "        'n_neighbors':[i for i in range(2, 11)],\n",
    "        'p':[i for i in range(1, 6)]\n",
    "    }\n",
    "]\n",
    "\n",
    "grid_search = GridSearchCV(knn_clf, param_grid, verbose=1)\n",
    "grid_search.fit(X_train, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.9823747680890538"
     },
     "metadata": {},
     "execution_count": 17
    }
   ],
   "source": [
    "grid_search.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "{'n_neighbors': 2, 'p': 2, 'weights': 'distance'}"
     },
     "metadata": {},
     "execution_count": 18
    }
   ],
   "source": [
    "grid_search.best_params_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "0.980528511821975"
     },
     "metadata": {},
     "execution_count": 20
    }
   ],
   "source": [
    "best_knn_clf = grid_search.best_estimator_\n",
    "best_knn_clf.score(X_test ,y_test )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "array([0.99543379, 0.96803653, 0.98148148, 0.96261682, 0.97619048])"
     },
     "metadata": {},
     "execution_count": 21
    }
   ],
   "source": [
    "cross_val_score(knn_clf, X_train, y_train, cv=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": "GridSearchCV(cv=5, error_score='raise-deprecating',\n             estimator=KNeighborsClassifier(algorithm='auto', leaf_size=30,\n                                            metric='minkowski',\n                                            metric_params=None, n_jobs=None,\n                                            n_neighbors=10, p=5,\n                                            weights='distance'),\n             iid='warn', n_jobs=None,\n             param_grid=[{'n_neighbors': [2, 3, 4, 5, 6, 7, 8, 9, 10],\n                          'p': [1, 2, 3, 4, 5], 'weights': ['distance']}],\n             pre_dispatch='2*n_jobs', refit=True, return_train_score=False,\n             scoring=None, verbose=1)"
     },
     "metadata": {},
     "execution_count": 22
    }
   ],
   "source": [
    "GridSearchCV(knn_clf, param_grid, verbose=1, cv=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ]
}